package com.manager.devicemanager.util;


import com.alibaba.fastjson2.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dyvmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dyvmsapi20170525.models.*;
import com.aliyun.tea.TeaException;
import com.manager.devicemanager.vo.SmsParamVO;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
public  class YuYInSmsUtils {
    private static final Logger logger = LoggerFactory.getLogger(YuYInSmsUtils.class);

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.ttsCode}")
    private  String ttsCode;

    public Boolean sendPhone(String phoneNumber, SmsParamVO smsParamVO){
        AsyncClient client=null;
        try {
            // Configure Credentials authentication information, including ak, secret, token
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                    .accessKeyId(accessKeyId)
                    .accessKeySecret(accessKeySecret)
                    //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                    .build());

            // Configure the Client
             client = AsyncClient.builder()
                    //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                    .credentialsProvider(provider)
                    //.serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // Endpoint 请参考 https://api.aliyun.com/product/Dyvmsapi
                                    .setEndpointOverride("dyvmsapi.aliyuncs.com")
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();
            SingleCallByTtsRequest singleCallByTtsRequest = SingleCallByTtsRequest.builder()
                    .calledNumber(phoneNumber)
                    .ttsCode(ttsCode)
                    .ttsParam("{\"device_name\":\""+smsParamVO.getDevice_name()+"时间："+smsParamVO.getTime()+"\",\"message\":\""+smsParamVO.getMessage()+"\",\"time\":\""+smsParamVO.getTime()+"\"}")
                    .playTimes(1) // 播放次数，默认1次
                    .build();


            // Asynchronously get the return value of the API request
            CompletableFuture<SingleCallByTtsResponse> response = client.singleCallByTts(singleCallByTtsRequest);
            // Synchronously get the return value of the API request
            SingleCallByTtsResponseBody body = response.get().getBody();
            String resp = response.get().getBody().getCode();
            if ("OK".equals(resp)) {
                return true;
            } else {
                logger.error("呼叫失败，错误码: {}, 错误信息: {}", resp, body.getMessage());
                return false;
            }


            // Asynchronous processing of return values
//        response.thenAccept(resp -> {
//            System.out.println(new Gson().toJson(resp));
//        }).exceptionally(throwable -> { // Handling exceptions
//            System.out.println(throwable.getMessage());
//            return null;
//        });
        } catch (TeaException error) {
            logger.error("呼叫过程中发生 TeaException", error);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("呼叫过程中发生未知异常", e);
        }finally {
            // Finally, close the client
            if (client!=null){
                client.close();
            }
        }
        return false;

    }

    public static void main(String[] args) {
        YuYInSmsUtils smsUtils = new YuYInSmsUtils();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "断电故障");
        jsonObject.put("time","2025-10-11 18:17:00");
        jsonObject.put("device_name", "设备");
        SmsParamVO smsParamVO = new SmsParamVO();
        smsParamVO.setMessage(jsonObject.getString("message"));
        smsParamVO.setTime(jsonObject.getString("time"));
        smsParamVO.setDevice_name("设备");
        smsUtils.sendPhone("13572293694", smsParamVO);
    }
}
